"""
  struct scoreType {
    scoreType( void );
    scoreType( const scoreType &s );
    scoreType &operator = ( const scoreType &s );
    bool isEmpty( void ) const;

    int numViews, numVotes, numComments, numFavs, numWishlist;
    double averageScore;
  };
"""

import pygtk
pygtk.require( '2.0' )
import gtk
import dpcDBs as dbs
from dpcDBs.log import log

from gui.helperFuncs import *

from sqlobject import sqlhub, connectionForURI

import gobject
from struct import *

from network import networkThread
from parsers import *
from time import sleep

class dpcImportDialog():
  imgRoot = "http://www.dpchallenge.com/image.php?IMAGE_ID="



  def updateProgress( self, pbobj = None ):
    p = float( self.progress ) / float( self.range )
    if p >= 1:
      p = 0
    self.progBar.set_fraction( p )
    return True





  def insertImage( self, src ):
    challenge = dbs.challengeTable.selectBy( int( self.imageID.get_text() ) )
    if not challenge:
      challenge = parseEntryPage( src )

    self.parse( challenge.challengeID )



  def process( self, w, data = None ):
    print "Downloading image details"
    self.network.addRequest( self.imgRoot + str( self.imageID.get_text() ) )

  def fileSelect( self, button = None, data = None ):
    log.i( self, 'Select file dialog opened' )
    dialog = gtk.FileChooserDialog( "Open..",
                                   None,
                                   gtk.FILE_CHOOSER_ACTION_OPEN,
                                   ( gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                                    gtk.STOCK_OPEN, gtk.RESPONSE_OK ) )
    dialog.set_default_response( gtk.RESPONSE_OK )


    filter = gtk.FileFilter()
    filter.set_name( "DPC Files" )
    filter.add_pattern( "*.dpc" )
    dialog.add_filter( filter )
    log.i( self, 'File set from dialog' )

    response = dialog.run()
    if response == gtk.RESPONSE_OK:
        print dialog.get_filename(), 'selected'
        if button:
          button.set_label( dialog.get_filename() )
        self.fileName = dialog.get_filename()
    elif response == gtk.RESPONSE_CANCEL:
        print 'Closed, no files selected'
    dialog.destroy()




  def downloadComplete( self, sender, url, param, resp ):
    ch = parseEntryPage( self.user, resp )
    print "Downloading complete";
    self.progBar.show_all()



    print "Removing entry rows"
    self.progBar.set_text( "Removing existing scores" )
    votes = dbs.voteTable.selectBy( challenge = ch )
    for i, vote in enumerate( votes ):
      self.progress = i
      dbs.voteTable.delete( vote.id )
    print "Done"




    print "Loading file"
    f = open( self.fileName, 'rb' )
    self.buf = f.read()
    n = int( float( len( self.buf ) ) / 32.0 )
    print "Done", n, "bytes read"



    print "Inserting rows"
    self.progBar.set_text( "Inserting new scores" )
    for i in range( n ):
      self.progress = i
      views, votes, comments, favourites, wishList, score = \
        unpack_from( 'iiiiid', self.buf, i * 32 )
      dbs.voteTable( challenge = ch,
                     votes = votes,
                     views = views,
                     score = score,
                     comments = comments,
                     favourites = favourites,
                     wishList = wishList )

    self.progBar.set_text( "Done" )
    print "Done"











  def __init__( self ):


    # GUI stuff
    self.win = gtk.Window()
    self.win.connect( "destroy", self.destroy )
    self.win.set_modal( True )
    self.win.set_title( "Import" )
    gtk.threads_init()
    self.progress = 1
    self.range = 1



    # set up the combo box
    self.user = None
    comboBox = gtk.combo_box_new_text()
    for user in dbs.userTable.select():
      comboBox.append_text( user.username )



    self.imageID = gtk.Entry()
    importb = gtk.Button( "Import into DB" )


    align = gtk.Alignment( 0.5, 0.5, 0, 0 )
    align.show()
    self.progBar = gtk.ProgressBar()
    align.add( self.progBar )
    self.progBar.show()
    self.timer = gobject.timeout_add( 100, self.updateProgress )


    t = gtk.Table()
    attachToTable( t, 0, "Select User", comboBox, self.userSelect, "changed" )
    attachToTable( t, 1, "Select file", gtk.Button( "Select file" ), self.fileSelect, "clicked" )
    attachToTable( t, 2, "Entry ID", self.imageID );
    attachToTable( t, 3, "", importb, self.process, "clicked" );
    attachToTable( t, 4, "", align );

    t.set_border_width( 2 )
    t.set_row_spacings( 2 )
    t.set_col_spacings( 2 )


    # Show everything
    t.show()
    self.win.add( t )
    self.win.show_all()
    comboBox.set_active( 0 )
    self.win.set_size_request( 500, 200 )

    # The network thread
    self.network = networkThread()
    self.network.connect( networkThread.signalDoneName, self.downloadComplete )
    self.network.start()

    self.set_modal( True )
    gtk.main()
    self.set_modal( False )


  # Unimportant callbacks
  def userSelect( self, b, data = None ):
    self.user = dbs.userTable.selectBy( username = b.get_active_text() ).getOne()

  def destroy( self, w = None ):
    self.win.hide()
    gtk.main_quit()
    return False




if __name__ == "__main__":
  sqlhub.processConnection = connectionForURI( 'sqlite:../dpchallenge.db' )
  dpcImportDialog()

